package com.iris.live.services.report.sources;

import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.models.CrmTopicModel;
import com.iris.live.services.data.models.Lsh经销商表Model;
import com.iris.live.services.data.repositories.CRMRepository;
import com.iris.live.services.data.repositories.CrmTopicRepository;
import com.iris.live.services.data.repositories.Lsh经销商表Repository;
import com.iris.live.services.report.Cell;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.report.Row;
import com.iris.live.services.report.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lusong on 2017/1/5.
 */
@Component("ExportDealerSurveyResultSource")
public class ExportDealerSurveyResultSource implements IExcelReportSource {

    private Logger logger = LoggerFactory.getLogger(ExportDealerSurveyResultSource.class);

    @Autowired
    private CRMRepository crmRepository;

    @Autowired
    private CrmTopicRepository crmTopicRepository;

    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;

    @Override
    public Sheet[] getSheets(Map<String, Object> context) {
        Sheet[] sheets = null;
        String permit = context.get("permit").toString();
        String version = context.get("version") == null ? null : context.get("version").toString();
        if (version != null && !"".equals(version)) {
            sheets = new Sheet[1];
            sheets[0] = new Sheet(version, permit, true);
        } else {
            String connectDateStart = context.get("connectDateStart") == null ? null : context.get("connectDateStart").toString();
            String connectDateEnd = context.get("connectDateEnd") == null ? null : context.get("connectDateEnd").toString();
            List list = crmRepository.findVersionForDealerAboutHistory(permit, connectDateStart, connectDateEnd);
            if (list != null && !list.isEmpty()) {
                sheets = new Sheet[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    Map map = (Map) list.get(i);
                    String getVersion = map.get("version") == null ? null : map.get("version").toString();
                    String getName = getVersion;
                    if (getVersion == null || "".equals(getVersion)) {
                        getVersion = "specialVersion";
                        getName = "调研问卷结果";
                    }
                    sheets[i] = new Sheet(getVersion, getName, true);
                }
            } else {
                sheets = new Sheet[0];
            }
        }
        return sheets;
    }

    @Override
    public List<Row> getSheetRows(Map<String, Object> context, Sheet sheet) {
        String permit = context.get("permit").toString();
        Lsh经销商表Model lsh经销商表Model = lsh经销商表Repository.getLshDistributorByPermit(permit);
        String connectDateStart = context.get("connectDateStart") == null ? null : context.get("connectDateStart").toString();
        String connectDateEnd = context.get("connectDateEnd") == null ? null : context.get("connectDateEnd").toString();
        String getVersion = sheet.getCode();
        if ("specialVersion".equals(getVersion)) {
            getVersion = null;
        }
        List values = getSurveyResult(permit, getVersion, connectDateStart, connectDateEnd);
        List<Row> list = new ArrayList<>();

        list.add(new Row());
        list.add(new Row());
        list.add(new Row());

        Cell[] cells = new Cell[4];
        cells[0] = new Cell(getVersion, 2);
        cells[1] = new Cell(lsh经销商表Model.get经销商名(), 5);
        cells[2] = new Cell(connectDateStart, 8);
        cells[3] = new Cell(connectDateEnd, 12);
        list.add(new Row(cells));

        list.add(new Row());
        list.add(new Row());

        for (Object o : values) {
            list.add(new Row(getCells(o)));
        }

        return list;
    }

    private Cell[] getCells(Object o) {
        Map<String, String> mapTopic = new HashMap<>();
        mapTopic.put("01", "单选");
        mapTopic.put("02", "多选");
        mapTopic.put("03", "开放");
        Map map = (Map) o;
        Cell[] cells = new Cell[73];
        cells[0] = new Cell(map.get("cusName") == null ? null : map.get("cusName").toString(), 1);
        cells[1] = new Cell(map.get("cusPhone") == null ? null : map.get("cusPhone").toString(), 2);
        cells[2] = new Cell(map.get("scName") == null ? null : map.get("scName").toString(), 3);
        for (int i = 0; i < 10; i++) {
            //cells[2 + i * 6] = new Cell(map.get("type" + (i + 1)) == null ? null : map.get("type" + (i + 1)).toString(), 3 + i * 6);
            String type = map.get("type" + (i + 1)) == null ? null : map.get("type" + (i + 1)).toString();
            cells[3 + i * 7] = new Cell(mapTopic.get(type), 4 + i * 7);
            cells[4 + i * 7] = new Cell(map.get("number" + (i + 1)) == null ? null : map.get("number" + (i + 1)).toString(), 5 + i * 7);
            cells[5 + i * 7] = new Cell(map.get("lead" + (i + 1)) == null ? null : map.get("lead" + (i + 1)).toString(), 6 + i * 7);
            cells[6 + i * 7] = new Cell(map.get("stem" + (i + 1)) == null ? null : map.get("stem" + (i + 1)).toString(), 7 + i * 7);
            cells[7 + i * 7] = new Cell(map.get("answer" + (i + 1)) == null ? null : map.get("answer" + (i + 1)).toString(), 8 + i * 7);
            cells[8 + i * 7] = new Cell(map.get("remark" + (i + 1)) == null ? null : map.get("remark" + (i + 1)).toString(), 9 + i * 7);
            cells[9 + i * 7] = new Cell(map.get("forwardEnding" + (i + 1)) == null ? null : map.get("forwardEnding" + (i + 1)).toString(), 10 + i * 7);
        }
        return cells;
    }

    private List getSurveyResult(String permit, String version, String connectDateStart, String connectDateEnd) {
        List list = new ArrayList();
        try {
            List<CrmTopicModel> listDealerTopic = null;
            //调研记录
            List listSurvey = crmRepository.findSurveyResult(permit, version, connectDateStart, connectDateEnd);
            if (listSurvey != null && !listSurvey.isEmpty()) {
                //经销商题库
                if (version != null && !"".equals(version)) {
                    listDealerTopic = crmTopicRepository.findTopicByVersion(permit, version);
                }
                //集团题库版本号
                List listGroupVersion = crmRepository.findVersionForGroupAboutHistory(permit, version, connectDateStart, connectDateEnd);
                //集团题库
                Map<String, List> mapGroup = new HashMap();
                if (listGroupVersion != null && !listGroupVersion.isEmpty()) {
                    for (Object o : listGroupVersion) {
                        Map map = (Map) o;
                        String groupVersion = map.get("groupVersion") == null ? null : map.get("groupVersion").toString();
                        List<CrmTopicModel> listGroupTopic = crmTopicRepository.findTopicByVersion("LSH", groupVersion);
                        mapGroup.put(groupVersion, listGroupTopic);
                    }
                }
                for (int i = 0; i < listSurvey.size(); i++) {
                    Map surveyResult = (Map) listSurvey.get(i);
                    String groupVersion = surveyResult.get("groupVersion") == null ? null : surveyResult.get("groupVersion").toString();

                    List groupTopic = new ArrayList();
                    for (Map.Entry<String, List> entry : mapGroup.entrySet()) {
                        if (entry.getKey().equals(groupVersion)) {
                            groupTopic = entry.getValue();
                        }
                    }

                    list.add(getData(surveyResult, groupTopic, listDealerTopic));
                }
            }
        } catch (Exception e) {
            logger.error("查询调研结果程序异常", e);
        }
        return list;
    }

    private Map getData(Map surveyResult, List<CrmTopicModel> groupTopic, List<CrmTopicModel> dealerTopic) {
        Map result = new HashMap();

        String topicId = surveyResult.get("topicId") == null ? "" : surveyResult.get("topicId").toString();
        String crm_remark = surveyResult.get("crm_remark") == null ? "" : surveyResult.get("crm_remark").toString();
        String answerId = surveyResult.get("answerId") == null ? "" : surveyResult.get("answerId").toString();
        String forwardEnding = surveyResult.get("forwardEnding") == null ? "" : surveyResult.get("forwardEnding").toString();

        String[] topicIds = topicId.split("___MARK___", -1);
        String[] crm_remarks = crm_remark.split("___MARK___", -1);
        String[] answerIds = answerId.split("___MARK___", -1);
        String[] forwardEndings = forwardEnding.split("___MARK___", -1);

        result.put("cusName", surveyResult.get("cusName") == null ? null : surveyResult.get("cusName").toString());
        result.put("cusPhone", surveyResult.get("cusPhone") == null ? null : surveyResult.get("cusPhone").toString());
        result.put("scName", surveyResult.get("scName") == null ? null : surveyResult.get("scName").toString());

        putData(result, groupTopic, topicIds, crm_remarks, answerIds, forwardEndings, 0);
        if (dealerTopic != null && !dealerTopic.isEmpty() && !StringUtils.isNullOrBlank(dealerTopic.get(0).getType())) {
            putData(result, dealerTopic, topicIds, crm_remarks, answerIds, forwardEndings, groupTopic.size());
        }
        return result;
    }

    private void putData(Map result, List<CrmTopicModel> dataList, String[] topicIds, String[] crm_remarks, String[] answerIds, String[] forwardEndings, int index) {
        for (int i = 0; i < dataList.size(); i++) {
            CrmTopicModel crmTopicModel = dataList.get(i);
            result.put("type" + (i + index + 1), crmTopicModel.getType());
            result.put("number" + (i + index + 1), crmTopicModel.getNumber());
            result.put("lead" + (i + index + 1), crmTopicModel.getLead());
            result.put("stem" + (i + index + 1), crmTopicModel.getStem());

            String id = crmTopicModel.getId() + "";
            for (int j = 0; j < topicIds.length; j++) {
                if (id.equals(topicIds[j])) {
                    result.put("answer" + (i + index + 1), answerIds[j]);
                    result.put("remark" + (i + index + 1), crm_remarks[j]);
                    result.put("forwardEnding" + (i + index + 1), forwardEndings[j]);
                }
            }
        }
    }
}
